<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="800px"
    @close="close"
  >
    <el-steps :space="200" :active="active" finish-status="success" simple>
      <el-step title="回收信息" icon="Edit" />
      <el-step title="货品信息" icon="UploadFilled" />
    </el-steps>
    <template v-if="active === '1'">
      <el-form
        ref="formRef"
        class="formRef"
        label-width="100px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="形式" prop="recycleWay">
          <el-radio-group v-model="form.recycleWay">
            <el-radio
              v-for="item in recycleWayList"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" required>
              {{ username || '--' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货方式" prop="receiveWay">
              <el-select
                v-model="form.receiveWay"
                class="m-2"
                placeholder="请选择收货方式"
              >
                <el-option
                  v-for="item in receiveWayList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货金额">
              <el-input
                v-model="form.receiveAmount"
                placeholder="请输入收货金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货日期" prop="receiveDatetime">
              <el-date-picker
                v-model="form.receiveDatetime"
                type="datetime"
                :disabled-date="disabledDate"
                placeholder="请选择日期"
                format="YYYY-MM-DD HH:mm:ss"
                time-format="HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="平台账号">
              <el-select
                v-model="form.plateAccountId"
                class="m-2"
                placeholder="请选择平台账号"
                @change="changeAccount"
              >
                <el-option
                  v-for="item in getAccountOperateList"
                  :key="item.id"
                  :label="item.platformAccount"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营人">
              <el-input
                v-model="form.operatorName"
                placeholder="请选择运营人"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="鉴定师" prop="valuerId">
              <UserSelect v-model="form.valuerId" :immediate-load="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品来源">
              <el-select
                v-model="form.productSource"
                class="m-2"
                placeholder="请选择货品来源"
              >
                <el-option
                  v-for="item in productSourceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 多选用户接口 -->
            <el-form-item label="参与人">
              <UserSelect
                v-model="form.partner"
                :immediate-load="true"
                :multiple="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户">
              <el-select
                v-model="form.customerId"
                class="m-2"
                placeholder="请选择客户"
              >
                <el-option
                  v-for="item in customerIdArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                class="m-2"
                placeholder="请选择入库仓库"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.warehouseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流水复核">
              <el-input
                v-model="form.billReview"
                placeholder="请输入流水复核"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            maxlength="250"
            placeholder="请输入备注"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
    </template>

    <template v-else>
      <el-form
        ref="formRef2"
        class="formRef"
        label-width="100px"
        :model="form2"
        :rules="rules2"
      >
        <el-form-item label="货品图片">
          <el-upload
            :action="action"
            list-type="picture-card"
            :headers="headers"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :show-file-list="false"
            limit="1"
          >
            <el-icon v-if="!form2.productPicture">
              <Plus />
            </el-icon>
            <img
              v-if="form2.productPicture"
              :src="form2.productPicture"
              alt=""
              style="width: 148px; height: 148px"
            />
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="form2.productPicture" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <!-- 货品编码： -->
        <el-form-item label="货品编码" prop="productCode" required>
          <el-input
            v-model="form2.productCode"
            placeholder="请输入货品编码"
            class="wd85"
          />
          <el-button text type="primary" @click="getProductCodeData">
            生成编码
          </el-button>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品名称" prop="productName" required>
              <el-input
                v-model="form2.productName"
                placeholder="请输入货品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品类" prop="productCategory" required>
              <el-select
                v-model="form2.productCategory"
                class="m-2"
                placeholder="请选择品类"
              >
                <el-option
                  v-for="item in productCategory"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="级别">
              <el-select
                v-model="form2.productRank"
                class="m-2"
                placeholder="请选择级别"
              >
                <el-option
                  v-for="item in productRankList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select
                v-model="form2.brandId"
                class="m-2"
                placeholder="请选择品牌"
                @change="getBrandSeriesList"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="系列">
              <el-select
                v-model="form2.seriesId"
                class="m-2"
                placeholder="请选择系列"
                :disabled="!form2.brandId"
              >
                <el-option
                  v-for="item in brandSeriesList"
                  :key="item.id"
                  :label="item.seriesName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="皮质">
              <el-input
                v-model="form2.seriesTexture"
                placeholder="请输入皮质"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="大小">
              <el-input v-model="form2.seriesSize" placeholder="请输入大小" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配件">
              <el-input
                v-model="form2.productMountings"
                placeholder="请输入配件"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="瑕疵">
              <el-input v-model="form2.productFlaw" placeholder="请输入瑕疵" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条形码">
              <el-input
                v-model="form2.productBarcode"
                placeholder="请输入条形码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="颜色">
              <el-input v-model="form2.seriesColor" placeholder="请输入颜色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年份">
              <el-input v-model="form2.seriesDate" placeholder="请输入年份" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="货品信息">
          <el-input
            v-model="form2.productInfo"
            maxlength="250"
            placeholder="请输入货品信息"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
    </template>
    <template v-if="active === '1'" #footer>
      <el-button text type="primary" @click="nextStep">下一步</el-button>
    </template>
    <template v-else #footer>
      <el-button text type="primary" @click="active = '1'">上一步</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { baseURL } from '@/config'
  import {
    addProduct,
    updateProduct,
    getAccountOperate,
    getProductCode,
  } from '@/api/receiveGoods'
  import { fetchDeptList } from '@/api/departmentManagement'
  import { defineProps } from 'vue'
  import { useUserStore } from '@/store/modules/user'
  import { fetchDictSelectList } from '@/api/dictionaryManagement'
  import { getList as brandList } from '@/api/brand'
  import { getEnableWarehouseList } from '@/api/warehouseInfo'
  import { getBrandSeries } from '@/api/series'

  export default defineComponent({
    name: 'AssetManagementAddEdit',
    // props: {
    //   assetCategoryData: Array,
    //   deptListData: Array
    // },
    components: {
      UserSelect: defineAsyncComponent(() =>
        import('@/components/biz/UserSelect')
      ),
    },
    emits: ['fetch-data'],
    setup(prop, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const userStore = useUserStore()
      const { token, username } = storeToRefs(userStore)
      const state = reactive({
        infoList: require('../../staticFile/static')[0],
        username,
        formRef: null,
        formRef2: null,
        headers: {},
        treeData: [],
        warehouseList: [],
        brandSeriesList: [],
        action: '',
        num: 1,
        getAccountOperateList: [],
        brandList: [],
        customerIdArr: [
          {
            label: 1,
            value: 1,
          },
          {
            label: 2,
            value: 2,
          },
        ],
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        form: {
          recycleWay: 'recycle',
        },
        form2: {
          // recycleWay: 'recycle',
        },
        active: '1',
        rules: {
          recycleWay: [
            { required: true, trigger: 'change', message: '请选择形式' },
          ],
          warehouseId: [
            { required: true, trigger: 'change', message: '请选择入库仓库' },
          ],
          receiveWay: [
            { required: true, trigger: 'change', message: '请选择收货方式' },
          ],
          receiveDatetime: [
            { required: true, trigger: 'change', message: '请选择收货日期' },
          ],
          receiveUserId: [
            { required: true, trigger: 'change', message: '请选择收货人' },
          ],
        },
        rules2: {
          productName: [
            { required: true, trigger: 'blur', message: '请输入货品名称' },
          ],
          productCode: [
            { required: true, trigger: 'blur', message: '请输入货品编码' },
          ],
          productCategory: [
            { required: true, trigger: 'change', message: '请选择品类' },
          ],
        },
        assetCategoryData: [],
        deptListData: [],
        dialogFormVisible: false,
        title: '',
        recycleWayList: [],
        receiveWayList: [],
        productSourceList: [],
        productCategory: [],
        productRankList: [],
      })
      const dialogImageUrl = ref('')
      const dialogVisible = ref(false)

      const props = defineProps({
        assetCategoryData: Array,
        deptListData: Array,
      })

      const handleRemove = (uploadFile, uploadFiles) => {
        console.log(uploadFiles.response)
      }
      const handleSuccess = (uploadFile) => {
        state.form2.productPicture = uploadFile.data.url
      }
      const handlePictureCardPreview = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url
        dialogVisible.value = true
      }
      const handledepartmentChange = (value) => {
        state.form.deptId = value[value.length - 1]
      }
      const handleClassifyChange = (value) => {
        state.form.cateId = value[value.length - 1]
      }
      const fetchDictLists = async (type, fields) => {
        const typeCode = {
          typeCode: type,
        }
        const { data: data } = await fetchDictSelectList(typeCode)
        state[fields] = data
      }

      // 可用仓库列表
      const setWarehouseList = async () => {
        const { data: data } = await getEnableWarehouseList({})
        state.warehouseList = data.list || []
      }

      // 系列列表
      const getBrandSeriesList = async (value) => {
        // 判断当前品牌是否更改，如果更改，系列清空
        const params = {
          brandId: value,
        }
        const { data: data } = await getBrandSeries(params)
        state.brandSeriesList = data.list || []
        state.form2.seriesId = ''
      }

      const getBrandList = async () => {
        try {
          state.listLoading = true
          const { data } = await brandList({})
          state.brandList = data.list || []
        } catch (e) {
          console.error(e)
        }
      }

      const showEdit = (row) => {
        state.form2 = {}
        if (!row) {
          state.form = {
            recycleWay: 'recycle',
          }
          state.title = '添加'
        } else {
          state.title = '编辑'
          const tempForm = JSON.parse(JSON.stringify(row))
          const imgArr = []
          if (tempForm.productPicture) {
            imgArr.push(tempForm.productPicture)
            tempForm.productPicture = imgArr
          }
          tempForm.deptTreePath &&
            (tempForm.deptId = transitionFunc(
              tempForm.deptTreePath,
              tempForm.deptId,
              1
            ).map(Number))
          tempForm.cateTreePath &&
            (tempForm.cateId = transitionFunc(
              tempForm.cateTreePath,
              tempForm.cateId,
              2
            ).map(Number))
          // 详情回显
          state.form.id = tempForm.id
          state.infoList.recoveryInfo.forEach((item) => {
            const string = item.value || item.key
            state.form[string] = tempForm[string]
          })
          state.infoList.itemInfo.forEach((item) => {
            const string = item.value || item.key
            state.form2[string] = tempForm[string]
          })
          // 回显参与人
          if (tempForm.partner) {
            let partner = tempForm.partner.split(',')
            partner = partner.map((item) => parseInt(item))
            state.form.partner = partner
          }
        }
        state.dialogFormVisible = true
      }

      const transitionFunc = (path, id) => {
        const newArr = path.split(',')
        if (path.length > 1) {
          newArr.shift()
        }
        newArr.push(id)
        return newArr
      }

      const getProductCodeData = async () => {
        // 生成编码
        try {
          const { data: data } = await getProductCode()
          state.form2.productCode = data
        } catch (e) {
          console.error(e)
        }
      }
      // 下一步
      const nextStep = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              state.active = '2'
            } catch (err) {
              console.error(err)
            }
          }
        })
      }

      const save = () => {
        state['formRef2'].validate(async (valid) => {
          if (valid) {
            if (state.title === '编辑') {
              if (Array.isArray(state.form.cateId)) {
                state.form.cateId =
                  state.form.cateId[state.form.cateId.length - 1]
              }
              if (Array.isArray(state.form.deptId)) {
                state.form.deptId =
                  state.form.deptId[state.form.deptId.length - 1]
              }
              // debugger;
              if (Array.isArray(state.form2.productPicture)) {
                state.form2.productPicture = state.form2.productPicture[0]
              }
            }
            try {
              const params = {
                ...state.form,
                ...state.form2,
              }
              if (Array.isArray(state.form.partner)) {
                params.partner = state.form.partner.join(',')
              }
              const { msg } =
                state.title === '添加'
                  ? await addProduct(params)
                  : await updateProduct(params)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (err) {
              console.error(err)
            }
          }
        })
      }

      const getAccountOperateList = async () => {
        try {
          const { data: data } = await getAccountOperate()
          state.getAccountOperateList = data.list || []
        } catch (e) {
          console.error(e)
        }
      }

      const changeAccount = (item) => {
        const index = state.getAccountOperateList.findIndex(
          (itemt) => itemt.id === item
        )
        state.form.operatorId = state.getAccountOperateList[index].operateId
        state.form.operatorName = state.getAccountOperateList[index].operateName
      }

      const close = () => {
        if (state['formRef2']) {
          state['formRef2'].resetFields()
        }
        state.active = '1'
        state.form = {
          recycleWay: 'recycle',
        }
        state.form2 = {}
        state.dialogFormVisible = false
      }

      const fetchdeptListDataData = async () => {
        try {
          const { data: data } = await fetchDeptList()
          state.deptListData = data
        } catch (e) {
          console.error(e)
        }
      }
      fetchdeptListDataData()
      onMounted(() => {
        fetchDictLists('recycleWay', 'recycleWayList')
        fetchDictLists('receiveWay', 'receiveWayList')
        fetchDictLists('productSource', 'productSourceList')
        fetchDictLists('productCategory', 'productCategory')
        fetchDictLists('productRank', 'productRankList')
        setWarehouseList()
        getBrandList()
        getAccountOperateList()
        getBrandSeriesList()
        const tokens = JSON.parse(JSON.stringify(token))
        state.headers['Authorization'] = `Bearer ${tokens._object.token}`
        state.action = `${baseURL}/zgyp-system/api/v1/files`
      })
      return {
        ...toRefs(state),
        showEdit,
        save,
        close,
        handledepartmentChange,
        handlePictureCardPreview,
        handleRemove,
        handleClassifyChange,
        handleSuccess,
        props,
        getProductCodeData,
        fetchDictLists,
        nextStep,
        getBrandList,
        changeAccount,
        getBrandSeriesList,
      }
    },
  })
</script>
<style scoped>
  .tree-container {
    width: 100%;
    min-height: 200px;
    border: 1px solid #dcdfe6;
  }

  .formRef {
    margin-top: 20px;
  }

  .wd85 {
    width: 85% !important;
  }

  :deep() {
    .el-select {
      width: 100%;
    }

    .el-input {
      width: 100%;
    }
  }
</style>
